/**
 * Created by qunxing.du on 2016/8/16.
 * Copyright 2016 汉威.智慧环保事业部 Limited.
 * All rights reserved.
 */
package com.hw.one.collect.pollution.server;

import com.alibaba.fastjson.JSON;
import com.hw.one.collect.message.Message;
import com.hw.one.collect.message.ResultMessage;
import com.hw.one.collect.util.ConvertUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.apache.log4j.Logger;

import java.util.Map;

/**
 * 认证处理器
 */
public class AuthenHandler extends ChannelInboundHandlerAdapter {
    private static Logger log = Logger.getLogger(AuthenHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.debug("接收数据："+ msg);
        Map<String,Object> dataMap = ConvertUtil.toMap(msg);

        String appId = (String) dataMap.get("appId");
        String appKey = (String) dataMap.get("appKey");

        if(!(Authen.getInstance().isAuthen(appId,appKey))){
            Message resultMsg = new ResultMessage("001","authen failed");
            ctx.writeAndFlush(JSON.toJSONString(resultMsg));
        }else {
            ctx.fireChannelRead(dataMap);
        }
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        log.error("异常：",cause);
        Message resultMsg = new ResultMessage("999","error");
        ctx.writeAndFlush(JSON.toJSONString(resultMsg));
    }

}
